package net.awpspace.walkman.utils;

import java.util.Stack;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

/**
 * A helper class to ease the navigation between views. Stores the previous
 * navigation steps in a Stack, has a reference to the running MIDlet and
 * manages the displaying of the views. Also quits the application when
 * navigating back but the stack is empty.
 */
public class BackStack {

	private static BackStack instance;

	private Stack backStack;
	private MIDlet midlet;

	private BackStack(MIDlet c) {
		midlet = c;
		backStack = new Stack();
	}

	/**
	 * Singleton
	 * 
	 * @param c
	 * @return
	 */
	public static BackStack getInstance(MIDlet c) {
		if (instance == null) {
			instance = new BackStack(c);
		}
		return instance;
	}

	/**
	 * Store a displayable to reuse
	 * 
	 * @param saved
	 */
	public void store(Displayable saved) {
		backStack.push(saved);
	}

	/**
	 * Navigate forward to newView
	 * 
	 * @param newView
	 */
	public void forward(Displayable newView) {
		Display display = Display.getDisplay(midlet);
		backStack.push(display.getCurrent());
		display.setCurrent(newView);
	}

	/**
	 * Navigate back one view. Quit if on the last view.
	 */
	public void back() {
		back(1);
	}

	/**
	 * Backs up multiple levels. Useful with Alerts.
	 * 
	 * @param levels
	 */
	public void back(int levels) {
		Displayable view = null;
		for (int i = 0; i < levels; i++) {
			if (!backStack.isEmpty()) {
				view = (Displayable) backStack.pop();
			} else {
				view = null;
			}
		}
		if (view != null) {
			Display.getDisplay(midlet).setCurrent(view);
		} else {
			midlet.notifyDestroyed();
		}
	}
}
